<?php
declare (strict_types = 1);

namespace app\middleware;

use think\Response;

class CorsMiddleware
{
    /**
     * 处理请求
     */
    public function handle($request, \Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS, PATCH',
            'Access-Control-Allow-Credentials' => 'true',
        ];

        // OPTIONS 请求直接返回
        if ($request->isOptions()) {
            return response()->header($headers);
        }

        // 正常请求增加 Expose-Headers
        $headers['Access-Control-Expose-Headers'] = 'Content-Disposition, Content-Length, X-Total-Count, Authorization, X-Pagination, X-RateLimit-Limit, X-RateLimit-Remaining';
        
        return $next($request)->header($headers);
    }
}
